class Compiler {
  constructor(vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }
  compile(el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if(this.isTextNode(node)) {
        this.compileText(node)
      } else if(this.isElementNode(node)) {
        this.compileElement(node)
      }

      if(node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }
  compileElement(node) {
    let attributes = node.attributes
    Array.from(attributes).forEach(attr => {
      let attrName = attr.name.substr(2)
      let key = attr.value
      if (attrName.indexOf(':') > 0) {
        let directName = attrName.substr(0, attrName.indexOf(':'))
        let eventName = attrName.substr(attrName.indexOf(':') + 1)
        this.update(directName, key, node, eventName)
      } else {
        this.update(attrName, key, node)
      }
      
    })
  }
  update(attrName, key, node, eventName) {
    let updateFn = this[attrName + 'Updater']
    updateFn && updateFn.call(this, this.vm[key], key, node, eventName)
  }
  textUpdater(value, key, node) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }
  modelUpdater(value, key, node) {
    node.value = value
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }
  htmlUpdater(value, key, node) {
    node.innerHTML = value
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }
  onUpdater(value, key, node, eventName) {
    node.addEventListener(eventName, () => {
      const func = this.vm.$options.methods[key]
      func && func()
    })
  }
  compileText(node) {
    let regx = /\{\{(.+?)\}\}/
    let value = node.textContent

    if(regx.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent = value.replace(regx, this.vm[key])
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue
      })
    }
  }
  isDirective(attrName) {
    return attrName.startWith('v-')
  }
  isTextNode(node) {
    return node.nodeType === 3
  }
  isElementNode(node) {
    return node.nodeType === 1
  }
}